from fastapi import APIRouter


def get_result():
    return {'code': 200, 'data': [], 'msg': 'ok'}


def get_id_router(path, peewee_model, update_item, tags=[], summary=['获取xx', '修改xx', '删除xx']):
    router = APIRouter()

    @router.get(path, tags=tags, summary=summary[0])
    def router_get(id: int):
        """根据id获取数据"""
        data = list(peewee_model.select().where(peewee_model.id == id).dicts())
        result = {'code': 200, 'data': data, 'msg': 'ok'}
        # 数据不存在
        if not data:
            result['code'] = 404
            result['msg'] = '要查找的数据不存在'
        return result

    @router.put(path, tags=tags, summary=summary[1])
    def router_put(id: int, item: update_item):
        """根据id修改数据"""
        result = get_result()
        peewee_model.update(**dict(item)).where(peewee_model.id == id).execute()
        return result

    @router.delete(path, tags=tags, summary=summary[2])
    def router_delete(id: int):
        """根据id删除数据"""
        result = get_result()
        peewee_model.delete().where(peewee_model.id == id).execute()
        return result

    return router


def get_list_router(path, peewee_model, add_item, tags=[], summary=['获取所有xx', '增加xx']):
    router = APIRouter()

    @router.get(path, tags=tags, summary=summary[0])
    def router_get():
        """获取所有数据"""
        data = list(peewee_model.select().dicts())
        result = {'code': 200, 'data': data, 'msg': 'ok'}
        # 数据不存在
        if not data:
            result['code'] = 404
            result['msg'] = '要查找的数据不存在'
        return result

    @router.post(path, tags=tags, summary=summary[1])
    def router_post(item: add_item):
        """新增数据"""
        result = get_result()
        peewee_model.create(**dict(item)).execute()
        return result

    return router


def set_model_router(app, model, item, model_english_name, model_chinese_name):
    """
    设置路由， 会自动生成五个路由： 获取所有， 增加一个， 获取一个， 修改一个， 删除一个
    :param app: fastapi的实例对象
    :param model: 要设置路由的模型
    :param item: 模型对应的请求体item，主要用于接收前端传过来的参数
    :param model_english_name: 模型英文名， 主要用于设置路径
    :param model_chinese_name: 模型中文名， 主要用于设置标签和api文档
    :return: None
    """
    id_router = get_id_router(
        "/{}/{}".format(model_english_name, 'id'),
        model, item,
        tags=[model_chinese_name],
        summary=[f'获取{model_chinese_name}', f'修改{model_chinese_name}', f'删除{model_chinese_name}'])
    app.include_router(id_router)
    list_router = get_list_router(
        "/{}s".format(model_english_name),
        model, item,
        tags=[model_chinese_name],
        summary=[f"获取所有{model_chinese_name}", f"增加{model_chinese_name}"]
    )
    app.include_router(list_router)
